/**
 * Translator.java
 * 
 * Created On: Nov 20, 2008
 * Created By: ## CHANGE IN JAVA->CODE STYLE->CODE TEMPLATES->New Java Files
 *
 * Copyright (C) 2008 University of Wisconsin Platteville - ResNet
 *
 * All rights are reserved to the University of Wisconsin Platteville
 */

package controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import model.Dialog;
import model.Language;
import model.TranslatedText;
import model.TranslationService;

public class Translator
{
	public static final String ENCODING = "UTF-8";
	
	public static TranslatedText execute( TranslationService service, 
			String input, Language fromLanguage, Language toLanguage ) 
				throws IOException
	{
		return execute( service, new Dialog( input, fromLanguage), toLanguage );
	}
	
	@SuppressWarnings("unchecked")
   public static TranslatedText execute( TranslationService service, 
			Dialog input, Language toLanguage ) throws IOException
	{
		
		URL url = null;
		TranslatedText translated = null;
		if ( service == TranslationService.GOOGLE )
		{
			String fromLang = input.getLanguage().getLanguageCode();
			String toLang = toLanguage.getLanguageCode();
			
			StringBuilder urlText = new StringBuilder();
			urlText.append("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0");
			urlText.append("&langpair=").append( fromLang ).append("%7C");
			urlText.append( toLang ).append( "&q=" );
			urlText.append( URLEncoder.encode( input.getText(), ENCODING) );

			url = new URL( urlText.toString() );
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			connection.addRequestProperty( "REFERER", "http://toxicdevelopment.com" );
			String response = receiveResponse( connection );
			JSONObject responseMap = (JSONObject)JSONValue.parse( response );
			String translatedText = ( (Map)responseMap.get("responseData"))
					.get("translatedText").toString();
			
			translated = new TranslatedText( input, new Dialog( translatedText,
					toLanguage ) );
		}
		
		return translated;
	}
	
	private static String receiveResponse( HttpURLConnection connection ) throws IOException
	{
		BufferedReader httpReader = new BufferedReader( 
				new InputStreamReader( connection.getInputStream() ) );
		
		StringBuilder response = new StringBuilder();
		while ( httpReader.ready() )
		{
			response.append( httpReader.readLine() + "\n" );
		}
		return response.toString();
	}
}
